package com.shinewind.sso.service;

import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shinewind.info.service.IUserInfoService;
import com.shinewind.info.service.IUserRoleService;
import com.shinewind.pojo.entity.UserInfo;
import com.shinewind.pojo.result.Result;
import com.shinewind.sso.entity.MyUser;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class MyUserDetailService implements UserDetailsService {
    @DubboReference
    private IUserInfoService iUserInfoService;
    @DubboReference
    private IUserRoleService iUserRoleService;

    @Override
    public UserDetails loadUserByUsername(String username){
        //根据用户名查找用户信息
        UserInfo userInfo = iUserInfoService.getUserInfoByUsername(username);

        if(ObjectUtil.isNull(userInfo)){
            throw new UsernameNotFoundException("用户"+username+"不存在");
        }
        else{
            //如果用户存在,根据用户id查找用户权限
            List<String> rolesList = iUserRoleService.getUserRoleByuId(userInfo.getUId());
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            if(rolesList != null && rolesList.size() > 0){
                for(String role : rolesList){
                    authorities.add(new SimpleGrantedAuthority(role));
                }
            }
            return MyUser.builder()
                    .uId(userInfo.getUId())
                    .userName(userInfo.getUserName())
                    .passWord(userInfo.getPassWord())
                    .authorities(authorities)
                    .build();
        }
    }

    public static void main(String[] args) {
        String password = new BCryptPasswordEncoder().encode("test123");
        System.out.println(password);
    }
}
